using System;
using System.Threading;
using StockTraderRI.Infrastructure.Messaging;
using StockTraderRI.Modules.News.Contract;

namespace StockTraderRI.Modules.News.Server
{
    public class NewsServer
    {
        private readonly IMessageBus bus;
        private readonly INewsRepository repository;

        private readonly Timer timer;

        public NewsServer(INewsRepository repository, IMessageBus bus)
        {
            this.bus = bus;
            this.repository = repository;

            timer = new Timer(OnTimerTick, null, TimeSpan.Zero, TimeSpan.FromSeconds(1));
        }

        private void OnTimerTick(object state)
        {
            var news = repository.FindNewsToPublish();
            if (news == null)
            {
                timer.Change(0, Timeout.Infinite);
                return;
            }

            bus.Publish(CreateMessage(news));
        }

        private NewsMessage CreateMessage(NewsDto dto)
        {
            return new NewsMessage
                       {
                           DatePublished = DateTime.Now,
                           News = dto
                       };
        }
    }
}